<template>
  <div class="index-box d-flex" ref="index">
    	<div class="leftBox" :style="{'width': leftTreeShow?'200px':'0px'}">
    		<div class="tree-box">
          <el-tree :data="treeList" node-key="categoryId" ref="tree" current-node-key="" :props="defaultProps" :expand-on-click-node="false" default-expand-all @node-click="handleNodeClick"></el-tree>
        </div>
    	</div>
       <div class="rightBox">
        <div class="mainBox" >
          <div class="search" ref="search">
            <el-form :inline="true" :model="searchForm" size="small" ref="searchForm" @submit.native.prevent
              class="demo-form-inline" id="searchBox">
              <MyLeftTreeRetract :leftTreeShow.sync="leftTreeShow"></MyLeftTreeRetract>
              <el-form-item prop="goodsCode">
                  <el-input v-model="searchForm.goodsCode" clearable placeholder="请输入商品编号"></el-input>
              </el-form-item>
              <el-form-item prop="goodsName">
                  <el-input v-model="searchForm.goodsName" clearable placeholder="请输入商品名称"></el-input>
              </el-form-item>
              <el-form-item prop="auditUserName">
                  <el-input v-model="searchForm.auditUserName" clearable placeholder="请输入审核人信息"></el-input>
              </el-form-item>

              <el-form-item prop="goodsState">
               <el-select filterable clearable v-model="searchForm.goodsState" placeholder="上下架">
                 <el-option label="已上架" value="1"></el-option>
                 <el-option label="已下架" value="2"></el-option>
               </el-select>
              </el-form-item>
              <el-form-item prop="address">
                  <el-cascader
                   placeholder="请选择区域"
                   size="small" clearable
                   :options="cascaderOptions"
                   v-model="searchForm.address"
                   @change="addressChange">
                  </el-cascader>
              </el-form-item>

              <el-form-item prop="time">
                <el-date-picker v-model="time" type="daterange" align="right" unlink-panels range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>

              <el-form-item prop="stockStatus">
               <el-select filterable clearable v-model="searchForm.stockStatus" placeholder="请选择状态">
                 <el-option label="正常" value="1"></el-option>
                 <el-option label="货源紧缺" value="2"></el-option>
               </el-select>
              </el-form-item>

              <el-form-item class="clearfix">
                <el-button type="primary" @click="handleSearch()" icon="el-icon-search">查询</el-button>
                <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
              </el-form-item>

              <el-form-item class="clearfix" style="margin-left:auto">
                 <MyRefresh/>
                <MyTableColumnSet :tableColumn.sync="tableColumn" :hideTableColumn.sync="hideTableColumn" :tableColumnType.sync="tableColumnType"></MyTableColumnSet>
              </el-form-item>

            </el-form>
          </div>
          <div class="table" ref="table">
            <el-table :data="dataList" style="width: 100%;"  border stripe :height="tableHeight" v-loading="loading"
             @selection-change="handleSelectionChange" @sort-change="handleTablechangeSort">
             <!-- <el-table-column type="selection" width="55" ></el-table-column> -->
              <el-table-column prop="goodsCode" label="商品编号" v-if="!hideTableColumn.includes('number')" width="120"></el-table-column>
              <el-table-column prop="name"  label="商品" v-if="!hideTableColumn.includes('img')" min-width="250">
                <template #default="scope">
                  <div class="goodsBox">
                    <div class="img">
                      <el-image :src="scope.row.goodsImage" fit="fill" v-image-preview="scope.row.goodsImage"></el-image>
                    </div>
                    <div class="goodsRight">
                      <div class="goodsName ellipsis-item">{{scope.row.goodsName}}</div>
                      <div class="goodsLabel">
                        <MyTableTag :tagList="scope.row.tagList"/>
                      </div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="productAddress" label="发货地" v-if="!hideTableColumn.includes('shopName')" width="170"  align="center"></el-table-column>
              <el-table-column prop="skuStocksList[0].originalPrice" label="原价(元)" v-if="!hideTableColumn.includes('original')" align="center" width="100"></el-table-column>
              <el-table-column prop="skuStocksList[0].salePrice" label="平台售价(元)" v-if="!hideTableColumn.includes('retail')"  align="center" width="120"></el-table-column>

              <el-table-column label="更新时间" align="center" prop="createTime" width="160" sortable v-if="!hideTableColumn.includes('time')">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.applyTime) }}</span>
                </template>
              </el-table-column>
             <el-table-column prop="auditUserName" label="审核人信息"  align="center"  width="120"></el-table-column>
              <el-table-column prop="goodsState" label="上/下架" v-if="!hideTableColumn.includes('upStatus')"  align="center"  width="100">
                <template #default="scope">
                    <span  >{{scope.row.goodsState=='2'?'已下架':'已上架'}}</span>
                </template>
              </el-table-column>

              <el-table-column prop="name" label="状态" v-if="!hideTableColumn.includes('status')" width="120"  align="center">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.stockState=='1'?'primary':'danger'" v-if="scope.row.stockState">{{scope.row.stockState=='1'?'正常':'货源缺货'}}</el-tag>
                </template>
              </el-table-column>

              <el-table-column prop="name" label="操作"  width="120" align="center" fixed="right">
                <template #default="scope">
                  <div class="verticalBtn">
                      <el-button
                        size="medium"
                        type="text"
                        icon="el-icon-document"
                        @click="handleLook(scope.$index, scope.row)"
                      >查看</el-button>
                      <el-button
                        size="medium"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleEditInventory(scope.$index, scope.row)"
                      >修改库存</el-button>

                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="page" ref="page">
            <MyPagination
               :total="total"
               :page.sync="searchForm.pageNum"
               :limit.sync="searchForm.pageSize"
               @pagination="dataInfo"
             />
          </div>
        </div>
      </div>

  <!-- /*修改库存*/	 -->
  <el-dialog :title="dialogTitle" width="1000px" v-dialogDrag :close-on-click-modal="false" :visible.sync="editInventoryVisible" @close="editInventoryVisible = false">
     <div class="table">
        <el-table :data="inventoryList" style="width: 100%;" :max-height="600"  border stripe >
            <el-table-column align="center" :prop="(index==0?'specNameOne':index==1?'specNameTwo':'specNameThree')" :label="item.specName" v-for="(item,index) in specKeyList"></el-table-column>
            <el-table-column align="center" prop="originalPrice" label="原价"></el-table-column>
            <el-table-column align="center" prop="costPrice" label="供货价"></el-table-column>
            <el-table-column align="center" prop="salePrice" label="平台售价"></el-table-column>
            <el-table-column align="center" prop="stockNum" label="库存" :render-header="renderHeader">
                <template #default="scope">
                	<el-input v-model="scope.row.stockNum" clearable placeholder="" v-Int></el-input>
                	<p class="red" style="margin: 0px;text-align: left;" v-show="scope.row.isInventory">请输入库存</p>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="cargoNo" label="货号"></el-table-column>
        </el-table>
     </div>
     <div slot="footer" class="dialog-footer">
       <el-button @click="editInventoryVisible = false" size="small">取 消</el-button>
       <el-button type="primary" @click="submitEditInventory()" size="small" :loading="userLoading">确 定</el-button>
     </div>
   </el-dialog>

  </div>
</template>

<script>
  import common from '@/api/api';
  import { goodsCategoryList,goodsStockList,updateStock,getGoodsStock } from '@/api/getData';
  import option from '../../common/option.js';
  import { regionData,CodeToText } from 'element-china-area-data';
  export default {
    data() {
      return {
        loading: false,
        userLoading: false,
        leftTreeShow:true,
        cascaderOptions:regionData,/*省市区插件数据*/
        tableColumn:[{/*自定义表格列*/
            name:'商品编号',
            value:'number'
        },{
            name:'商品图片',
            value:'img'
        },{
            name:'商品名称',
            value:'name'
        },{
            name:'发货地',
            value:'shopName'
        },{
            name:'原价(元)',
            value:'original'
        },{
            name:'零售价(元)',
            value:'retail'
        },{
            name:'标签',
            value:'label'
        },{
            name:'状态',
            value:'status'
        },{
            name:'更新时间',
            value:'time'
        }],
        hideTableColumn:[],/*自定义表格列需要隐藏的*/
        tableColumnType:'staffManagement',/*自定义表格列类型传参*/
        searchForm: {
          goodsCategoryId:'',
          goodsCode:"",
          goodsName:'',
          stockStatus:'',
          address:[],
          auditUserName:'',
          goodsState:'',

          provinceId:'',
          cityId:'',
          areaId:'',

          pageNum: 1,
          pageSize: 20,
          orderByColumn:'',
          isAsc:'',
        },
        treeList: [{categoryId: "",name: "商品分类",children: []}],
        tableHeight:0,//table 高度
        dataList:[],
        total: 0,
        defaultProps: {
           children: 'children',
           label: 'name'
        },
        multipleSelection: '',
        userFormVisible:false,
        dialogTitle:'',
        user: {
          id: '',
          parentId:'',

          themeName:'',
          img:'',

          typeName:'',
          parentType:"",
        },
        rules: {
          themeName: [{required: true, message: '主题名称不能为空',trigger: 'blur'}],
          typeName: [{required: true, message: '分类名称不能为空',trigger: 'change'}]
        },

        inventoryList:[],/*库存列表*/
        editInventoryVisible:false,
        time:[],
        specKeyList:[],
      }
    },
    computed: {
      pickerOptions: () => {
        return option.pickerOptions;
      }
    },

    mounted() {
      // this.dataInfo();
      // this.getSelect();
      this.$nextTick(() => {
          this.tableHeight = this.$refs.index.offsetHeight - this.$refs.search.offsetHeight  - this.$refs.page.offsetHeight - 35;
      })
    },
    methods: {
    	renderHeader(h) {
        return (
               <div>
                    <span class="red">*</span><span>库存</span>

               </div>
            )
      },
      getSelect(){
        goodsCategoryList().then(res=>{
          this.treeList[0].children = res.data;
        });
       //this.getSelectList('hot_goods_audit_status').then(res=>{ this.goods_audit_status = res.data; })
      },
      async handleEditInventory(index,row){/*修改库存*/
        try {
          this.dialogTitle = `商品'${row.goodsName}'的库存信息`;
          const result = await getGoodsStock({goodsId: row.goodsId});
          let data = result.data.skuStockList;
          data.map(item=>{
          	item.isInventory = false;//
          })
          this.inventoryList = result.data.skuStockList;
          this.specKeyList = result.data.specKeyList;
          console.log(this.specKeyList);
          this.editInventoryVisible = true;
        } catch (err) {
          console.log(err)
        }
      },
      submitEditInventory(){

      	for(let i=0;i<this.inventoryList.length;i++){
      		console.log(this.inventoryList[i].stockNum);
      		if(!this.inventoryList[i].stockNum && this.inventoryList[i].stockNum!='0'){
      			this.inventoryList[i].isInventory = true;
      			this.$message.error('请填写库存');
      			return;
      		}else{
      			this.inventoryList[i].isInventory = false;
      		}
      	}
        this.userLoading = true;
        updateStock(this.inventoryList).then((result) => {
          if (result.code == 200) {
            this.$message.success(result.msg);
            this.editInventoryVisible = false;
            this.dataInfo();
          } else {
            this.$message.error(result.msg);
          }
          this.userLoading = false;
        })
      },
      addressChange(arr) {
          console.log(arr);
          console.log(CodeToText[arr[0]], CodeToText[arr[1]], CodeToText[arr[2]]);
      },

      handleLook(index,row){
        this.$router.push({path:'/shop/shopDetails',query:{goodsId:row.goodsId}});
      },

      handleTablechangeSort (column, prop, order) {/*表格排序*/
         this.searchForm.orderByColumn =  column.prop;
         this.searchForm.isAsc = column.order;
         this.dataInfo();
      },

      resetQuery() {
        this.resetForm("searchForm");
        this.dataInfo();
      },

      async dataInfo() {
        try {
          let data = this.addDateRange(this.searchForm, this.time, 'applyTimeStart', 'applyTimeEnd');
          this.loading = true;

          const result = await goodsStockList(data);
          if (result.code == 200) {
            this.total = result.total;
            this.dataList = result.rows;
          } else {
            this.$message.error(result.msg);
          }

          this.loading = false;
        } catch (err) {
          this.loading = false;
          console.log(err)
        }
      },

      handleSearch() {
        this.searchForm.pageNum = 1;
        this.dataInfo();
      },

      handleNodeClick(data){/*树节点点击事件*/
       this.searchForm.goodsCategoryId =  data.categoryId;
       this.handleSearch();
      },

      handleSelectionChange(val) {
        this.multipleSelection = selection.map(item => item.id);
        console.log(this.multipleSelection);
      },

    }
  }
</script>

<style scoped lang="scss">
  .activeCheckedBox{
      border-top: 1px solid #ddd;
      padding: 10px;
      height: 52px;
  }
  .index-box{
    padding:0px!important;
    margin-left:0px;
  }
  .tree-box /deep/ .el-tree-node{
     background: #D8E4DD;
  }
  .tree-box> /deep/ .el-tree>.el-tree-node{
    padding:3px;
  }
  .tree-box> /deep/ .el-tree .is-current{
    background:#fff;
  }
  .table-box{
    padding:15px
  }
  .down{
    color: #909399;
    cursor: pointer;
    text-decoration:underline;
  }
  .down:hover{
    color: #a6a9ad;
  }
  .up{
    color:#61997A;
    cursor: pointer;
    text-decoration:underline;
  }
  .up:hover{
    color:#81ad95;
  }
  .treeTitle{
    color: #606266;
    font-size: 15px;
    margin:20px 20px 0 20px
  }
</style>
